package com.lxch.gdwxp.demoController;

import com.lxch.gdwxp.wxpay.service.WXPayService;
import com.lxch.gdwxp.wxpay.utils.HttpRequestUtil;
import com.lxch.gdwxp.wxpay.wxpayconfig.WXPConstants;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/auth")
public class WXAuthorController {

    private final static Logger log = LoggerFactory.getLogger(WXAuthorController.class);

    @Resource
    private WXPayService wxPayService;

    /**
     * 用户授权
     * 授权获取到code后会跳转到获取oppenId方法
     *
     * @return 重定向到获取用户code页面
     */
    @RequestMapping("/getCode")
    //@ResponseBody
    public String getCode(HttpSession session) {
        Object openid = session.getAttribute("openid");//先获取是否已经有oppnid了
        if (openid != null && openid != "") {
            System.out.println("已经获取过openid了就直接返回到index页面==========");
            return "index";
        }
        System.out.println("请检查些getcodeURL是否正确===============++++++" + wxPayService.getCodeUrl());
        return "redirect:" + wxPayService.getCodeUrl();//重定向
    }

    /**
     * 设置oppenId
     *
     * @return
     */
    @RequestMapping(value = "/domain/setOppenId", method = RequestMethod.POST)
    //@ResponseBody
    public String setOppenId(HttpServletRequest req, Model model) {
        String oppenid = (String) req.getSession().getAttribute("openid");
        if (oppenid == null || oppenid == "") {
            //那个放到服务器根路径中的中转页面get-weixin-code.html已经获取到了code
            String code = req.getParameter("code");
            log.info("==============调用/domain/setOppenId===========授权code:" + code);
            Map<String, Object> result = new HashMap<>();
            if (StringUtils.isNotBlank(code)) {
                result = wxPayService.setOppenId(code);//调用微信获取OppenId的api

                if (result.get("status").equals("200")) {
                    System.out.println("wxauthorcontroller66行获取到用户oppenId:" + result.get("oppenId"));
                    req.getSession().setAttribute("openid", result.get("oppenId"));// 得到oppenId,放到session中，
                    String userinfo_url = WXPConstants.userinfo_url.replace("OPPENID",result.get("oppenId")+"")
                            .replace("ACCESSTOKEN",result.get("access_token")+"");
//                    String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + result.get("access_token") + "&openid=" + result.get("oppenId") + "&lang=" + "zh_CN";
                    JSONObject m = HttpRequestUtil.httpsRequestToJsonObject(userinfo_url, "GET", null);//拉取用户信息
                    System.out.println("==============拉取用户信息返回jsonobject:" + m);
                    JSONObject myJson = JSONObject.fromObject(m);
                    System.out.println("==============得到tokenjsonobject  token========" + myJson);
                    Map token = myJson;//得到token
                    System.out.println("jsonobject转换成  map========" + token);
                    System.out.println(token.get("province") + "" + token.get("city"));
                    req.getSession().setAttribute("tokenn", m);
                    return "index";
                }
            } else { // 获取code失败
                log.info("=================授权失败，没有获取到code");
                req.setAttribute("msg", "授权失败,没有获取到code");
//            result.put("status", 400);
//            result.put("msg", "用户授权失败！");
                model.addAttribute("status", 400);
                model.addAttribute("msg", "用户授权失败！");
                return "error";
            }
            System.out.println("获取用户信息error++_+_+_+_+_+_+");
            return "error";
        } else {
            return "index";
        }
    }

    @RequestMapping("/papa/getOppenId")
    @ResponseBody
    public String getOppenId(HttpSession session) {
        String openid = (String) session.getAttribute("openid");
        if (StringUtils.isBlank(openid)) {
            return "";
        }
        return openid;
    }
}
